import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from horseanalysis.lib.base import BaseController, render
from horseanalysis.model.race import Race
from horseanalysis.model.race_batch import RaceBatch

from horseanalysis.model.betting_scheme import BettingScheme
from horseanalysis.model.probability_sets.quinella_probability_result import QuinellaProbabilityResult
from horseanalysis.model.probability_sets.quinella_place_probability_result import QuinellaPlaceProbabilityResult
from horseanalysis.model.probability_sets.place_probability_result import PlaceProbabilityResult

from horseanalysis.lib.hkjc_fetcher.current_race_fetcher import CurrentRaceFetcher
from horseanalysis.lib.hkjc_fetcher.sample_race_fetcher import SampleRaceFetcher
from horseanalysis.lib.hkjc_fetcher.result_fetcher import ResultFetcher
from horseanalysis.lib.hkjc_fetcher.race_day_fetcher import RaceDayFetcher
from datetime import date, datetime

log = logging.getLogger(__name__)

class DataController(BaseController):

  def index(self):
    redirect_to(controller='dashboard', action='index')
  
  def create_race(self):
    if Race.all().count() == 0:
      Race.create_dummy_race()
      return "Complete"
    else:
      return "Failed"
  
  def create_sample_data(self):
    if Race.all().count() == 0:
      fetcher = SampleRaceFetcher()
      fetcher.fetch_sample_race_data()
      BettingScheme.create_default_scheme()
      
      return "Completed"
    else:
      return "Cannot create sample data create it is not a empty environment"
    
  def fetch_results(self):
    num_fetched = ResultFetcher.get_result_for_those_needed()
    return '<?xml version="1.0"?><RESULT>%d races result fetched</RESULT>' % num_fetched
      
  def fetch_fresh_data(self):
    fetcher = CurrentRaceFetcher()
    if fetcher.should_fetch_current_race():
      fetcher.fetch_current_race_data()
      return '<?xml version="1.0"?><RESULT>Completed</RESULT>'
    else:
      return '<?xml version="1.0"?><RESULT>Not within 30 minutes</RESULT>'
  
  def fetch_race_day(self):
    fetcher = RaceDayFetcher()
    if fetcher.create_race_if_need():
      return "Completed"
    else:
      return "Failed"
  
  def update_race_batch_probability(self):
    batches = RaceBatch.get_race_batches_not_completed_probability_set()
    i = 0
    for batch in batches:
      if i <= 1:
        if PlaceProbabilityResult.prerequisites_checking(batch):
          try:
            PlaceProbabilityResult.analyze_batch_if_not_existed(batch)
            QuinellaProbabilityResult.analyze_batch_if_not_existed(batch)
            QuinellaPlaceProbabilityResult.analyze_batch_if_not_existed(batch)
      
            PlaceProbabilityResult.update_all_gain_offset_if_have_result(batch)
            QuinellaProbabilityResult.update_all_gain_offset_if_have_result(batch)
            QuinellaPlaceProbabilityResult.update_all_gain_offset_if_have_result(batch)
          except:
            PlaceProbabilityResult.incomplete_related_race_batch_probability_result(batch)
            QuinellaProbabilityResult.incomplete_related_race_batch_probability_result(batch)
            QuinellaPlaceProbabilityResult.incomplete_related_race_batch_probability_result(batch)
        else:
          PlaceProbabilityResult.incomplete_related_race_batch_probability_result(batch)
          QuinellaProbabilityResult.incomplete_related_race_batch_probability_result(batch)
          QuinellaPlaceProbabilityResult.incomplete_related_race_batch_probability_result(batch)
      else:
        break
      
      i+=1
    return "Completed"
  
  def total_race_batch(self):
    return str(RaceBatch.all().count())
  
  def remain_probability_calc(self):
    return str(RaceBatch.get_race_batches_not_completed_probability_set().count())